package com.couldsail.takeaway.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.couldsail.takeaway.context.BaseContext;
import com.couldsail.takeaway.mapper.CouponMapper;
import com.couldsail.takeaway.mapper.UserCouponMapper;
import com.couldsail.takeaway.pojo.dto.UserCouponReceiveDTO;
import com.couldsail.takeaway.pojo.entity.Coupon;
import com.couldsail.takeaway.pojo.entity.UserCoupon;
import com.couldsail.takeaway.pojo.vo.CouponVO;
import com.couldsail.takeaway.pojo.vo.UserCouponVO;
import com.couldsail.takeaway.service.CouponService;
import com.couldsail.takeaway.utils.UniqueIdGenerator;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import com.couldsail.takeaway.constant.CouponConstant;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class CouponServiceImpl implements CouponService {
    private final CouponMapper couponMapper;
    private final UserCouponMapper userCouponMapper;

    @Override
    public List<UserCouponVO> getUserCoupons(UserCouponReceiveDTO userCouponReceiveDTO) {
        String userId = BaseContext.getCurrentId();
        // 查询用户的优惠券关联记录
        // 查询用户优惠券
        LambdaQueryWrapper<UserCoupon> userCouponWrapper = Wrappers.lambdaQuery();
        userCouponWrapper.eq(UserCoupon::getUserId, userId)
                .eq(UserCoupon::getShopId,userCouponReceiveDTO.getShopId())
                .in(UserCoupon::getStatus,Arrays.stream(userCouponReceiveDTO.getStatus().split(","))
                .collect(Collectors.toList()));
        List<UserCoupon> userCoupons = userCouponMapper.selectList(userCouponWrapper);
        List<UserCouponVO> userCouponVOS = new ArrayList<>();
        // 转换并排序
        List<UserCouponVO> collect = userCoupons.stream()
                .map(item -> {
                    UserCouponVO userCouponVO = new UserCouponVO();
                    BeanUtils.copyProperties(item, userCouponVO);

                    CouponVO couponVO = new CouponVO();
                    BeanUtils.copyProperties(couponMapper.selectById(item.getCouponId()), couponVO);
                    userCouponVO.setCouponVO(couponVO);

                    return userCouponVO;
                })
                .sorted(Comparator.comparing(userCouponVO -> userCouponVO.getCouponVO().getValue(), Comparator.reverseOrder()))
                .toList();
        if (BigDecimal.valueOf(userCouponReceiveDTO.getTotalAmount()).compareTo(BigDecimal.valueOf(0.0))==0) {
            userCouponVOS =collect;
        }else {
            List<UserCouponVO> finalUserCouponVOS = userCouponVOS;
            collect.forEach(item->{
                if (BigDecimal.valueOf(userCouponReceiveDTO.getTotalAmount()).compareTo(item.getCouponVO().getMinPurchase())>0){
                    finalUserCouponVOS.add(item);
                }
            });
        }



        return userCouponVOS;
    }

    @Transactional
    public void obtainCoupon(String couponId) {
        String userId = BaseContext.getCurrentId();
        // 查询优惠券是否存在且有效
        Coupon coupon = couponMapper.selectById(couponId);
        if (coupon == null) {
            throw new RuntimeException(CouponConstant.NOT_COUPON);
        }

        // 检查优惠券是否在有效期内
        LocalDateTime now = LocalDateTime.now();
        if (now.isBefore(coupon.getValidStart()) || now.isAfter(coupon.getValidEnd())) {
            throw new RuntimeException(CouponConstant.COUPON_NOT_TIME);
        }
        
        // 检查优惠券是否已被领完
        if (coupon.getUsed() >= coupon.getTotal()) {
            throw new RuntimeException(CouponConstant.COUPON_NOT_INVENTORY);
        }
        
        // 检查用户是否已领取过该优惠券
        LambdaQueryWrapper<UserCoupon> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserCoupon::getUserId, userId)
                .eq(UserCoupon::getCouponId, couponId);
        if (userCouponMapper.selectCount(wrapper) > 0) {
            throw new RuntimeException(CouponConstant.COUPON_HAVA_INVENTORY);
        }
        
        // 创建用户优惠券记录
        userCouponMapper.insert(UserCoupon.builder()
                        .id(UniqueIdGenerator.generateUniqueId())
                        .userId(userId)
                        .couponId(couponId)
                        .status(CouponConstant.COUPON_STATUS_UNUSED)
                        .obtainedTime(now)
                .build());
        
        // 更新优惠券已使用数量
        coupon.setUsed(coupon.getUsed() + 1);
        couponMapper.updateById(coupon);
    }

    @Override
    public CouponVO detailCoupon(String couponId) {
        CouponVO couponVO = new CouponVO();
        Coupon coupon = couponMapper.selectById(couponId);
        BeanUtils.copyProperties(coupon,couponVO);
        return couponVO;
    }
} 